<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Config;
use think\Cookie;
use think\Db;
use think\Hook;
use think\Session;
use think\Validate;
set_time_limit(0);

/**
 * 会员中心
 */
class User extends Frontend
{

    protected $layout = 'default';
    protected $noNeedLogin = ['login', 'register', 'third'];
    protected $noNeedRight = ['*'];
    protected $relationSearch = true;

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

        $ucenter = get_addon_info('ucenter');
        if ($ucenter && $ucenter['state']) {
            include ADDON_PATH . 'ucenter' . DS . 'uc.php';
        }

        //监听注册登录注销的事件
        Hook::add('user_login_successed', function ($user) use ($auth) {
            $expire = input('post.keeplogin') ? 30 * 86400 : 0;
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);
        });
        Hook::add('user_register_successed', function ($user) use ($auth) {
            Cookie::set('uid', $user->id);
            Cookie::set('token', $auth->getToken());
        });
        Hook::add('user_delete_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
        Hook::add('user_logout_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->view->assign('title', __('User center'));
        return $this->view->fetch();
    }

    /**
     * 注册会员
     */
    public function register()
    {
        $this->error('');
        $url = $this->request->request('url');
        if ($this->auth->id)
            $this->success(__('You\'ve logged in, do not login again'), $url);
        if ($this->request->isPost()) {
            $username = $this->request->post('username');
            $password = $this->request->post('password');
            $email = $this->request->post('email');
            $mobile = $this->request->post('mobile', '');
            $captcha = $this->request->post('captcha');
            $token = $this->request->post('__token__');
            $rule = [
                'username'  => 'require|length:3,30',
                'password'  => 'require|length:6,30',
                'email'     => 'require|email',
                'mobile'    => 'regex:/^1\d{10}$/',
                'captcha'   => 'require|captcha',
                '__token__' => 'token',
            ];

            $msg = [
                'username.require' => 'Username can not be empty',
                'username.length'  => 'Username must be 3 to 30 characters',
                'password.require' => 'Password can not be empty',
                'password.length'  => 'Password must be 6 to 30 characters',
                'captcha.require'  => 'Captcha can not be empty',
                'captcha.captcha'  => 'Captcha is incorrect',
                'email'            => 'Email is incorrect',
                'mobile'           => 'Mobile is incorrect',
            ];
            $data = [
                'username'  => $username,
                'password'  => $password,
                'email'     => $email,
                'mobile'    => $mobile,
                'captcha'   => $captcha,
                '__token__' => $token,
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
            }
            if ($this->auth->register($username, $password, $email, $mobile)) {
                $synchtml = '';
                ////////////////同步到Ucenter////////////////
                if (defined('UC_STATUS') && UC_STATUS) {
                    $uc = new \addons\ucenter\library\client\Client();
                    $synchtml = $uc->uc_user_synregister($this->auth->id, $password);
                }
                $this->success(__('Sign up successful') . $synchtml, $url ? $url : url('user/index'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('url', $url);
        $this->view->assign('title', __('Register'));
        return $this->view->fetch();
    }

    /**
     * 会员登录
     */
    public function login()
    {
        $url = $this->request->request('url');
        if ($this->auth->id)
            $this->success(__('You\'ve logged in, do not login again'), $url);
        if ($this->request->isPost()) {
            $account = $this->request->post('account');
            $password = $this->request->post('password');
            $keeplogin = (int)$this->request->post('keeplogin');
            $token = $this->request->post('__token__');
            $rule = [
                'account'   => 'require|length:3,50',
                'password'  => 'require|length:6,30',
                '__token__' => 'token',
            ];

            $msg = [
                'account.require'  => 'Account can not be empty',
                'account.length'   => 'Account must be 3 to 50 characters',
                'password.require' => 'Password can not be empty',
                'password.length'  => 'Password must be 6 to 30 characters',
            ];
            $data = [
                'account'   => $account,
                'password'  => $password,
                '__token__' => $token,
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return FALSE;
            }
            if ($this->auth->login($account, $password)) {
                $synchtml = '';
                ////////////////同步到Ucenter////////////////
                if (defined('UC_STATUS') && UC_STATUS) {
                    $uc = new \addons\ucenter\library\client\Client();
                    $synchtml = $uc->uc_user_synlogin($this->auth->id);
                }

                $this->success(__('Logged in successful') . $synchtml, $url ? $url : url('user/client'),['id'=>$this->auth->id,'token' => $this->request->token()]);
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('url', $url);
        $this->view->assign('title', __('Login'));
        return $this->view->fetch();
    }

    /**
     * 注销登录
     */
    function logout()
    {
        //注销本站
        $this->auth->logout();
        $synchtml = '';
        ////////////////同步到Ucenter////////////////
        if (defined('UC_STATUS') && UC_STATUS) {
            $uc = new \addons\ucenter\library\client\Client();
            $synchtml = $uc->uc_user_synlogout();
        }
        $this->success(__('Logout successful') . $synchtml, url('user/index'));
    }

    /**
     * 个人信息
     */
    public function profile()
    {
        $this->view->assign('title', __('Profile'));
        return $this->view->fetch();
    }

    /**
     * 修改密码
     */
    public function changepwd()
    {
        if ($this->request->isPost()) {
            $oldpassword = $this->request->post("oldpassword");
            $newpassword = $this->request->post("newpassword");
            $renewpassword = $this->request->post("renewpassword");
            $token = $this->request->post('__token__');
            $rule = [
                'oldpassword'   => 'require|length:6,30',
                'newpassword'   => 'require|length:6,30',
                'renewpassword' => 'require|length:6,30|confirm:newpassword',
                '__token__'     => 'token',
            ];

            $msg = [
            ];
            $data = [
                'oldpassword'   => $oldpassword,
                'newpassword'   => $newpassword,
                'renewpassword' => $renewpassword,
                '__token__'     => $token,
            ];
            $field = [
                'oldpassword'   => __('Old password'),
                'newpassword'   => __('New password'),
                'renewpassword' => __('Renew password')
            ];
            $validate = new Validate($rule, $msg, $field);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return FALSE;
            }

            $ret = $this->auth->changepwd($newpassword, $oldpassword);
            if ($ret) {
                $synchtml = '';
                ////////////////同步到Ucenter////////////////
                if (defined('UC_STATUS') && UC_STATUS) {
                    $uc = new \addons\ucenter\library\client\Client();
                    $synchtml = $uc->uc_user_synlogout();
                }
                $this->success(__('Reset password successful') . $synchtml, url('user/login'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        $this->view->assign('title', __('Change password'));
        return $this->view->fetch();
    }

    /**
     * 子级账户管理
    **/
    public function son(){
        $this->assign('feedlist',build_select('row[sel]',['电话拒接','电话空号或停机','客户不需要','客户有意向'],0,['class' => 'form-control selectpicker']));
        return $this->view->fetch();
    }

    /**
     * 客户管理
    **/
    public function client(){

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            $this->model = model('ApplyBet');

            $map = [];

            if ($this->auth->parent_id == 0){
                $map['user_id'] = $this->auth->id;
            }else{
                $map['user_id'] = $this->auth->parent_id;
                $map['operate_id'] = 0;
            }

            $stime = time();
            $etime = time()-3600*72;
            // 查询大于当前时间 小于72小时的数据

            $map['apply_bet.create_time'] = ['between time',[$etime,$stime]];
//            $map['apply_bet.bet_time'] = ['between time',[$etime,$stime]];

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            // 延迟显示时间
            $total = $this->model
                ->with('apply')
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->count();

            // 使用构造器查询

            $list = $this->model
                ->with('apply')
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        return $this->view->fetch();
    }

    // 认领
    public function operate($ids=''){

        if ( $ids ){
            // 如果是父级 就不让领取
            if ($this->auth->parent_id == 0 ){
                $this->error('父级不能领取');
            }

            // 认领
            $this->model = model('ApplyBet');

            // 如果被认领过了
            if ( $this->model->where('id',$ids)->value('operate_id') > 0){
                $this->error('已经被认领过了');
            };

            if ( $this->model->where(['user_id'=>$this->auth->parent_id,'id'=>$ids])->update(['operate_id'=>$this->auth->id]) ){
                $this->success('认证成功');
            }else{
                $this->error('认证失败');
            }

        }
    }

    /**
     * 我的认领客户
    **/
    public function myclient(){

        $map = [];

        if ($this->auth->parent_id == 0){
            $this->error('您不能进来');
        }else{
            $map['operate_id'] = $this->auth->id;
        }

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            $this->model = model('ApplyBet');



//            $map['apply_bet.create_time'] = ['>','apply_bet.create_time'.$time];


            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            // 延迟显示时间
            $total = $this->model
                ->with('apply')
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->count();

            // 使用构造器查询

            $list = $this->model
                ->with('apply')
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 问题反馈
    **/
    public function feedback(){
        if ( $this->request->isAjax() ){
            $id = $this->request->post('ids',0);
            $status = $this->request->post('status',0);
            $type = $this->request->post('type',0);

            if ($this->auth->parent_id == 0){
                $pid = $this->auth->id;
            }else{
                $pid = $this->auth->parent_id;
            }


            // 参数
            if (!$id || !$status || !$type){
                $this->error('参数错误');
            }

            // 更改数据
            $this->model = model('ApplyBet');

            if ($type == 2){
                if ( $this->model->where(['user_id'=>$pid,'id'=>$id])->update(['feedback'=>$status]) ){
                    $this->success('反馈成功');
                }else{
                    $this->error('反馈成功');
                }

            }else if ($type == 1){

                if ( $this->model->where(['user_id'=>$pid,'id'=>$id])->update(['status'=>1]) ){
                    $this->success('订单更新成功');
                }else{
                    $this->error('订单更新成功');
                }
            }else{
                $this->error('更新失败');
            }
        }
    }

    /**
     * 购买
    **/
    public function order(){
        if ($this->request->isAjax())
        {
            // 是否父级
            if ($this->auth->parent_id == 0){
                $id = $this->auth->id;
            }else{
                $id = $this->auth->parent_id;
            }

            $this->takeout();
            // 进件数量
            $user = model('user');
            $Bet = model('ApplyBet');
            $user2 = $user->get($id);
            $residue = $user2->score;   //   剩余积分

            if (!$user2){
                $this->error('用户不存在');
            }

            // 今日注册量
            $RegNumber = $Bet->dayreg($id);

            // 扣除积分
            $grade = config('site.grade');
            if ( !$id ){
                $this->error('id不能为空');
            }


            // 排除客户最大的使用次数
            $map['bignumber']  = ['<',Db::raw('neednumber')];

            // 只看今天的数据
            $map['update_time'] = ['>=',strtotime(date('Y-m-d',time()))];

            // 今日注册的数量 是否已经大于用户进件数
            if (  $this->auth->into_the_number <= $RegNumber->total){
                $this->error('');
            }

            // 今天还需要进件多少次
            $number =  $this->auth->into_the_number - $RegNumber->total;

            // 所有可用的用户 是否够分配
            $maxcount = db('apply a')->where($map)->where('id','NOT IN',function ($query) use ($id){
                $query->table('jd_apply_bet')->where('user_id',$id)->field('apply_id');
            })->count();

            $maxid = db('apply a')->where($map)->where('id','NOT IN',function ($query) use ($id){
                $query->table('jd_apply_bet')->where('user_id',$id)->field('apply_id');
            })->max('id');

            if ( !($maxcount >= $number)){
                $number = $maxcount;
            }

            // 查看用户还是否购买过此订单了

            // 商户最后读取客户的一次的id
            $last_id = db('config')->where('name','apply_last_id')->value('value');

            $ret = db('apply a')->where($map)->where('a.id','>',$last_id)->where('id','NOT IN',function ($query) use ($id){
                $query->table('jd_apply_bet')->where('user_id',$id)->field('apply_id');
            })->limit($number)->select();

            // 数量
            $total = count($ret);

            if ($number > $total){
                while (1){
                    if ($total >= $number){
                        break;
                    }else{

                        // 如果数据不足就重新拼接
                        $n = ($number - $total);
                        $ret2 = db('apply a')->where($map)->where('a.id','>',0)->where('id','NOT IN',function ($query) use ($id){
                            $query->table('jd_apply_bet')->where('user_id',$id)->field('apply_id');
                        })->limit($n)->select();

                        $ret = array_merge($ret,$ret2);
                        $total += count($ret2);
                    }
                }
            }


            // 本次扣除积分计算

            // 如果用户积分不够就退出
            // 如果积分不够


            // 加入购买订单
            foreach ($ret as  $k=>$v){

                // 大于配置文件中的 的扣除4分
                if ($v['zhimafen'] >= $grade['max']){
                    $deduct = 4;
                }else{
                    //小于于580 的扣除3分
                    $deduct = 3;
                }
                if ( $user2->score < $deduct ){
                    $this->error('积分不足哦');
                }


                // 延迟显示
                $time = 3600*$user2->delay_show_time;

                $addData = [
                    'apply_id'=>$v['id'],
                    'user_id'=>$id,
                    'score'=>$deduct,
                    'apply_info'=>serialize($v),
                    'create_time'=>$v['update_time']+$time,
                    'bet_time'=>time(),
                    'admin_id'=>$this->auth->id
                ];

                Db::table('jd_apply_bet')->insert($addData);

                // 今日进件+1
                $RegNumber->total++;


                $residue = $residue-$deduct;

                // 积分详情
                $addScore = [
                    'user_id'=>$id,
                    'residue'=>$residue,
                    'score'=>$deduct,
                    'type'=>1,
                    'msg'=>'购买客户',
                    'admin_id'=>$this->auth->id,
                    'create_time'=>$v['update_time']+$time,
                    'takeout'=>0
                ];
                db('score_detail')->insert($addScore);


                // 扣除积分
                $user2->score -= $deduct;

                model('apply')->where('id',$v['id'])->setInc('bignumber');
            }

            // 记录最后的 ID
            $end_id = end($ret);

            if ($maxid == $end_id['id']){
                db('config')->where('name','apply_last_id')->update(['value'=>0]);
            }else{
                db('config')->where('name','apply_last_id')->update(['value'=>$end_id['id']]);
            }

            $this->success('ok');
        }
    }

    /**
     * 扣除积分
    **/
    public function takeout(){
        $this->model = model('Score');

        if ($this->auth->parent_id == 0){
            $map['user_id'] = $this->auth->id;
        }else{
            $map['user_id'] = $this->auth->parent_id;
        }

        // 要等时间到才能扣除积分
        $map['create_time'] = ['<=',time()];
        $map['takeout'] = 0;
        $map['type'] = 1;
        // 查询还没有扣除的
        $sum = $this->model->where($map)->sum('score');
        if ($sum > 0){
            model('user')->where('id',$map['user_id'])->setDec('score',$sum);
            $this->model->where($map)->update(['takeout'=>1]);
        }
        return true;
    }

    /**
     * 设置
    **/
    public function data(){
        $this->view->engine->layout(false);
        return $this->view->fetch();
    }

    /**
     * 消费记录
    **/
    public function score(){

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            $this->model = model('ScoreDetail');

            $map = [];

            if ($this->auth->parent_id == 0){
                $map['user_id'] = $this->auth->id;
            }else{
                $map['user_id'] = $this->auth->parent_id;
            }


            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            // 延迟显示时间
            $total = $this->model
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->count();

            // 使用构造器查询

            $list = $this->model
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        return $this->view->fetch();
    }

}
